// @Author EthanScriptOn
// @Desc
package extend_param_builder

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_param_collector"
	"regexp"
	"strings"
)

type SqlParamsBuilder struct {
}

func (s *SqlParamsBuilder) Build(params interface{}) (interface{}, error) {
	sqlParams, ok := params.(*extend_param_collector.SqlParams)
	if !ok {
		return nil, fmt.Errorf("params is not SqlParams")
	}
	sqlCommand, err := s.ReplacePlaceholders(sqlParams)
	if err != nil {
		return nil, err
	}
	if sqlCommand == "" {
		return nil, fmt.Errorf("sql command is empty")
	}
	return sqlCommand, nil
}

func FoundPlaceholder(commandStr string) map[string]string {
	placeholderMap := make(map[string]string)
	re := regexp.MustCompile(`\$\{([^\}]+)\}`)
	matches := re.FindAllStringSubmatch(commandStr, -1)
	for _, match := range matches {
		if len(match) != 2 {
			continue
		}
		placeholderMap[match[0]] = match[1]
	}
	return placeholderMap
}

func (s *SqlParamsBuilder) ReplacePlaceholders(sqlParams *extend_param_collector.SqlParams) (string, error) {
	if sqlParams.CommandArgs == nil {
		return "", fmt.Errorf("commandArgs is nil")
	}
	commandStr := sqlParams.Command.String()
	parts := FoundPlaceholder(commandStr)
	for complete, part := range parts {
		if part != "" && strings.HasPrefix(complete, "${") && strings.HasSuffix(complete, "}") {
			placeholderName := part
			value, ok := sqlParams.CommandArgs[placeholderName]
			if !ok {
				return "", fmt.Errorf("no value found for placeholder: %s", placeholderName)
			}
			commandStr = strings.ReplaceAll(commandStr, complete, value)
		}
	}
	return commandStr, nil
}
